package com.mark.controller.common;

import com.mark.common.Const;
import com.mark.common.ServerResponse;
import com.mark.enums.UserStateEnum;
import com.mark.pojo.Admin;
import com.mark.pojo.User;
import com.mark.util.CookieUtil;
import com.mark.util.JsonUtil;
import com.mark.util.RedisShardedPoolUtil;
import com.sun.net.httpserver.HttpServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Mark on 2018/4/21.
 *当前用户的存储，取出
 */
@Slf4j
public class CurrentUser {

    //从Redis缓存中获取当前用户：Tomcat集群时需要用到这个方法
    public static ServerResponse getCurrentUser(HttpServletRequest httpServletRequest){
        try {
            String loginToken = CookieUtil.readLoginToken(httpServletRequest);//获取Cookie中的value值sessionId
            if (StringUtils.isEmpty(loginToken)) {
                return ServerResponse.createByErrorMessage("用户未登录");
            }
            String userJsonStr = RedisShardedPoolUtil.get(loginToken);
            User currentUser = JsonUtil.string2Obj(userJsonStr, User.class);
            if (currentUser == null) {
                return ServerResponse.createByNeedLogin();
            }
            return ServerResponse.createBySuccess(currentUser);
        }catch (Exception e){
            log.error("从缓存中获取当前用户信息异常：{}",e.toString());
            return ServerResponse.createByErrorMessage("不好意思  出错了！！！");
        }
    }

    //保存当前用户信息到redis中时间为30分钟
    public static void setCurrentUser(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String sessionId, User currentUser){
        sessionId  = "user"+sessionId;
        CookieUtil.writeLoginToken(httpServletResponse,sessionId,httpServletRequest);//往response中添加Cookie，value值为sessionId
        RedisShardedPoolUtil.setEx(sessionId, JsonUtil.obj2String(currentUser), Const.RedisCacheExtime.REDIS_SESSION_EXTIME);//写入redis缓存（key=sessionId，value=user.toString）
    }

    //从当前的session中获取当前用户：单个Tomcat时用这个方法
    public static ServerResponse getCurrentUserBySession(HttpSession session){
        User currentUser = (User) session.getAttribute(UserStateEnum.CURRENT_USER.getStateInfo());
        if (currentUser == null) {
            return ServerResponse.createByNeedLogin();
        }
        return ServerResponse.createBySuccess(currentUser);
    }
    //保存当前用户到session中
    public static void setCurrentUserInSession(HttpSession session,User CurrentUser){
        session.setAttribute(UserStateEnum.CURRENT_USER.getStateInfo(),CurrentUser);
    }

    public static void setCurrentAdmin(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String sessionId, Admin currentAdmin) {
        sessionId  = "admin"+sessionId;
        CookieUtil.writeAdminLoginToken(httpServletResponse,sessionId,httpServletRequest);//往response中添加Cookie，value值为sessionId
        RedisShardedPoolUtil.setEx(sessionId, JsonUtil.obj2String(currentAdmin), Const.RedisCacheExtime.REDIS_SESSION_EXTIME);//写入redis缓存（key=sessionId，value=user.toString）
    }
}
